/*
 * Copyright 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.sockets.client.impl;

import com.google.gwt.sockets.client.BinarySocket;
import com.google.gwt.sockets.client.SocketListener;
import com.google.gwt.sockets.client.SocketException;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * <p>The Java-based implementation of binary sockets. It uses Java Applet as proxy to obtain necessary
 * socket funactionality from Java.</p>
 *
 * <p>This class uses <b>javabinary.jar</b> archive with Java Applet which must be signed.</p>
 *
 * <p>You should use methods of {@link com.google.gwt.sockets.client.SocketsFactory SocketsFactory} to
 * create instances of binary sockets. Use this class directly only for specific purposes.</p>
 *
 * @see com.google.gwt.sockets.client.BinarySocket
 * @see com.google.gwt.sockets.client.SocketsFactory
 * @author Aleksey Lagoshin
 */
public class JavaBinarySocketImpl extends BinarySocket {

  private static final String TAG =
          "<applet name='{0}' ARCHIVE = 'javabinary.jar' CODEBASE = '.' width='1' height='1' " +
          "style='position: absolute; left: -500px; top: -500px'" +
          "code='com.google.gwt.sockets.applets.java.BinaryApplet.class' mayscript><param name='id' value='{1}'></applet>";

  private HTML javaTag;

  /**
   * Default constructor.
   */
  protected JavaBinarySocketImpl() {
  }

  /**
   * Standart constructor for socket classes.
   *
   * @param listener a listener for the socket
   */
  public JavaBinarySocketImpl(SocketListener listener) {
    super(listener);
  }

  /**
   * Adds Java Applet to the page.
   *
   * @param id the ID of this applet
   */
  protected void initImplementation(int id) {
    String appletName = "javabinApp_" + id;

    javaTag = new HTML();
    javaTag.setHTML(TAG.replaceAll("[{][0][}]", appletName).replaceAll("[{][1][}]", String.valueOf(id)));

    RootPanel.get().add(javaTag);
  }

  public void shutdown() throws SocketException {
    checkSocket();
    shutdownImpl();
    RootPanel.get().remove(javaTag);
    super.shutdown();
  }

  protected native void shutdownImpl() /*-{
    this.@com.google.gwt.sockets.client.AbstractSocket::socketObj.shutdown();
  }-*/;

  protected String getPrefix() {
    return "javabin_";
  }

}
